﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using Data.Common;
using Data.Enum;
using Data.Model;
using Data.ViewModel;

namespace DataAccess.BikeManage
{
    /// <summary>
    /// 停车区域管理
    /// </summary>
    public class LockArea : DbBase, ILockArea
    {
        /// <summary>
        /// 获取停车区域
        /// </summary>
        /// <param name="areaId">区域id</param>
        /// <returns></returns>
        public ResultInfo<IList<jsh_Area>> GetLockArea(int areaId)
        {
            var result = new ResultInfo<IList<jsh_Area>>();
            try
            {
                using (SqlCommand command = GetProCommand())
                {
                    command.CommandText = "sp_GetLockArea";
                    command.Parameters.Add("@id", SqlDbType.Int).Value = areaId;

                    var ds = new DataSet();
                    var da = new SqlDataAdapter(command);
                    da.Fill(ds);

                    IList<jsh_Area> areas = (from DataRow d in ds.Tables[0].Rows select new jsh_Area(d)).ToList();
                    result.Obj = areas;
                }
            }

            catch (Exception e)
            {
                result.ResultNumber = ResultEnum.Error;
                result.Describe = e.Message;
            }

            return result;
        }

        /// <summary>
        /// 分页获取停车区域
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="areaName">停车区域的名称</param>
        /// <returns></returns>
        public ResultInfo<PagingDataSet<LockAreaView>> GetLockAreas(int pageIndex, int pageSize, string areaName)
        {
            var result = new ResultInfo<PagingDataSet<LockAreaView>>();
            try
            {
                using (SqlCommand myCommand = GetProCommand())
                {
                    myCommand.CommandText = "Common_GetPagingRecords";
                    var fromClause = new StringBuilder();
                    fromClause.Append("jsh_Area with (nolock) ");
                    var whereClause = new StringBuilder();
                    if (!string.IsNullOrEmpty(areaName))
                    {
                        whereClause.Append(string.Format(" and name like '%{0}%' ", areaName));
                    }
                    if (whereClause.Length > 3)
                    {
                        whereClause.Remove(0, 5);
                    }

                    myCommand.Parameters.Add("@PageIndex", SqlDbType.Int).Value = pageIndex - 1;
                    myCommand.Parameters.Add("@PageSize", SqlDbType.Int).Value = pageSize;
                    myCommand.Parameters.Add("@FromClause", SqlDbType.VarChar, 1024).Value = fromClause.ToString();
                    myCommand.Parameters.Add("@SelectFields", SqlDbType.VarChar, 512).Value = "*";
                    myCommand.Parameters.Add("@WhereClause", SqlDbType.NVarChar, 4000).Value = whereClause.ToString();
                    myCommand.Parameters.Add("@SortField", SqlDbType.VarChar, 256).Value = "id";
                    myCommand.Parameters.Add("@SortFieldIsDesc", SqlDbType.Bit).Value = true;
                    myCommand.Parameters.Add("@ReturnRecordCount", SqlDbType.Bit).Value = true;
                    myCommand.Parameters.Add("@MaxRecords", SqlDbType.Int).Value = int.MaxValue;
                    myCommand.Parameters.Add("@TotalRecords", SqlDbType.Int).Direction = ParameterDirection.Output;
                    myCommand.Parameters.Add("@ReverseOrder", SqlDbType.Bit).Direction = ParameterDirection.Output;

                    var dataSet = new DataSet();
                    var da = new SqlDataAdapter(myCommand);
                    da.Fill(dataSet);

                    var list = dataSet.Tables[0].Rows.Cast<DataRow>().Select(dataRow => new jsh_Area(dataRow)).Where(temp => temp.TranByConstructFlag).ToList();

                    var totalRecords = Convert.ToInt32(myCommand.Parameters["@TotalRecords"].Value);
                    var reverseOrder = Convert.ToBoolean(myCommand.Parameters["@ReverseOrder"].Value);

                    if (reverseOrder)
                        list.Reverse();

                    var listView = PopulateLockArea(list);

                    result.ResultNumber = ResultEnum.Success;
                    result.Obj = new PagingDataSet<LockAreaView> { PageIndex = pageIndex, PageSize = pageSize, Records = listView, TotalRecords = totalRecords };
                }
            }
            catch (Exception e)
            {
                result.ResultNumber = ResultEnum.Error;
                result.Describe = e.Message;
            }
            return result;
        }

        /// <summary>
        /// 删除停车区域
        /// </summary>
        /// <param name="id">停车区域的id</param>
        /// <returns></returns>
        public ResultInfo<bool> DeleteLockArea(int id)
        {
            var result = new ResultInfo<bool>();
            try
            {
                string sql = string.Format("delete from jsh_Area where id={0}", id);
                int temp = ExcuteSql(sql);
                if (temp > 0)
                {
                    result.ResultNumber = ResultEnum.Success;
                    result.Obj = true;
                }
                else
                {
                    result.ResultNumber = ResultEnum.Error;
                    result.Obj = false;
                }
            }
            catch (Exception)
            {

            }
            return result;
        }

        /// <summary>
        ///  如果area的id存在，那就是修改，如果不存在那就是新增
        /// </summary>
        /// <param name="area">停车区域的信息</param>
        /// <returns></returns>
        public ResultInfo<int> CreateOrUpdateLockArea(jsh_Area area)
        {
            var result = new ResultInfo<int>();
            try
            {
                string sql = string.Empty;
                if (area != null)
                {
                    if (area.id > 0)
                    {
                        sql = string.Format("UPDATE jsh_Area SET [area]='{0}' where [id]={1} select {1} id", area.Area, area.id);
                    }
                    else
                    {
                        string check = string.Format("select id from jsh_Area where area='{0}'", area.Area);
                        DataSet dt = ExcuteSqlDataSet(check);
                        if (dt != null && dt.Tables[0].Rows.Count > 0)
                        {
                            result.ResultNumber = ResultEnum.Error;
                            result.Describe = "已经存在同名停车区域，请重新输入";
                        }
                        else
                        {
                            sql = string.Format("insert into jsh_Area([area]) values('{0}') select @@identity id", area.Area);
                        }
                    }
                    if (!string.IsNullOrEmpty(sql))
                    {
                        DataSet dataSet = ExcuteSqlDataSet(sql);
                        if (dataSet != null && dataSet.Tables[0].Rows.Count == 1)
                        {
                            int temp = Convert.ToInt32(dataSet.Tables[0].Rows[0]["id"]);
                            if (temp > 0)
                            {
                                result.ResultNumber = ResultEnum.Success;
                                result.Obj = temp;
                            }
                            else
                            {
                                result.ResultNumber = ResultEnum.Error;
                                result.Describe = "更新数据失败";
                            }
                        }
                    }
                }
                else
                {
                    result.ResultNumber = ResultEnum.Error;
                    result.Describe = "请输入有效数据";
                }
            }
            catch (Exception e)
            {
                result.ResultNumber = ResultEnum.Error;
                result.Describe = e.Message;
            }
            return result;
        }

        private static List<LockAreaView> PopulateLockArea(IEnumerable<jsh_Area> areas)
        {
            int i = 0;
            var area = new List<LockAreaView>();
            foreach (jsh_Area lockArea in areas)
            {
                i++;
                area.Add(new LockAreaView
                {
                    Serial = i,
                    AreaName = lockArea.Area,
                    ID = lockArea.id
                });
            }
            return area;
        }

    }
}
